#include <getopt.h>
#include <iostream>
#include <sstream>

#include "logger.h"
#include "socket_connector.h"
#include "socket_connection.h"

int main(int argc, char **argv)
{
    int port = 2222;
    std::string address = "127.0.0.1";
    std::stringstream ss;
    while (true) {
        int optidx = 0;
        struct option options[] = {
            {"port",    required_argument, 0, 'p'},
            {"address", required_argument, 0, 'a'},
            {0,         0,                 0,  0 },
        };

        int c = getopt_long(argc, argv, "p:a:", options, &optidx);
        if (c == -1) {
            break;
        }

        switch (c) {
            case 'a':
                ss.clear();
                ss << optarg;
                ss >> address;
                if (!ss) {
                    return 1;
                }
                break;

            case 'p':
                ss.clear();
                ss << optarg;
                ss >> port;
                if (!ss) {
                    return 1;
                }
                break;

            default:
                LOGGER() << "getopt_long: " << c << std::endl;
                break;
        }
    }

    SocketConnector connector;
    connector.SetAddress(address);
    connector.SetPort(port);
    auto connection = connector.Connect();
    if (connection == nullptr) {
        return 1;
    }

    while (true) {
        char cmd[1024];
        std::cout << "# ";
        std::cin.getline(cmd, sizeof(cmd));
        if (!std::cin) {
            break;
        }
        connection->Send(cmd);

        std::string message = "";
        connection->Recv(message);
        std::cout << message << std::endl;
    }
    return 0;
}
